// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '@/views/home.vue'; // 主布局组件
import Login from '@/components/login.vue'; // 登录组件
import UserHome from '@/views/User_home.vue'; // 业主首页组件
import Dashboard from '@/components/Dashboard.vue'; // Dashboard 组件
import AnnouncementList from '@/components/AnnouncementList.vue'; // 公告列表组件
import ActivityList from '@/components/ActivityList.vue'; // 动态列表组件
import PropertyList from '@/components/PropertyList.vue'; // 楼盘管理组件
import UnitManagement from '@/components/UnitManagement.vue'; // 单元管理组件
import UserManagement from '@/components/UserManagement.vue'; // 用户管理组件

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },

  {
    path: '/home',
    component: Home,
    meta: { requiresAuth: true, role: '管理员' }, // 管理员权限
    children: [
      { path: 'dashboard', name: 'Dashboard', component: Dashboard, meta: { requiresAuth: true, role: '管理员' } },
      { path: 'properties', name: 'PropertyList', component: PropertyList, meta: { requiresAuth: true, role: '管理员' } },  // 楼盘信息
      { path: 'units', name: 'UnitManagement', component: UnitManagement, meta: { requiresAuth: true, role: '管理员' } },  // 单元管理
      { path: 'user_management', name: 'UserManagement', component: UserManagement, meta: { requiresAuth: true, role: '管理员' } },  // 用户管理
      { path: 'announcements', name: 'AnnouncementList', component: AnnouncementList, meta: { requiresAuth: true, role: '管理员' } }, // 公告管理
      { path: 'activities', name: 'ActivityList', component: ActivityList, meta: { requiresAuth: true, role: '管理员' } }, // 动态管理
      { path: '', redirect: 'dashboard' },
    ],
  },

  {
    path: '/user_home',
    component: UserHome,
    meta: { requiresAuth: true, role: '业主' }, 
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const user = JSON.parse(localStorage.getItem('user')) || {};

  // 检查是否需要授权
  if (to.meta.requiresAuth && !token) {
    alert('请先登录');
    return next('/login'); // 未登录跳转到登录页面
  }

  // 检查角色权限
  if (to.meta.role) {
    if (!user.role) {
      console.warn('用户角色未定义，无法验证权限');
      alert('登录状态无效，请重新登录');
      return next('/login');
    }

    if (user.role !== to.meta.role) {
      console.warn(`访问被拒绝：用户角色为 ${user.role}，需要角色为 ${to.meta.role}`);
      alert('您无权访问该页面');
      return next('/login'); // 角色不匹配跳转到登录页面
    }
  }

  next(); // 允许访问
});

export default router;
